<template>
  <div>
    <!-- 设备查询条件 -->
    <el-form @submit.prevent="query" :model="queryDevice" label-width="120px" inline>
      <el-form-item label="设备 ID:" prop="deviceId">
        <el-input v-model="queryDevice.deviceId" />
      </el-form-item>
      <el-form-item label="设备状态:" prop="status">
        <el-select v-model="queryDevice.status" placeholder="请选择状态">
          <el-option label="库存中" value="in_stock" />
          <el-option label="使用中" value="in_use" />
          <el-option label="维修中" value="under_maintenance" />
          <el-option label="已报废" value="disposed" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备名称:" prop="deviceName">
        <el-input v-model="queryDevice.deviceName" />
      </el-form-item>
      <el-form-item label="设备型号:" prop="model">
        <el-input v-model="queryDevice.model" />
      </el-form-item>
      <el-form-item label="设备分类:" prop="category">
        <el-input v-model="queryDevice.category" />
      </el-form-item>
      <el-form-item label="设备品牌:" prop="brand">
        <el-input v-model="queryDevice.brand" />
      </el-form-item>
      <el-form-item label="序列号:" prop="serialNumber">
        <el-input v-model="queryDevice.serialNumber" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 设备列表 -->
    <el-table v-if="devices.length > 0" :data="devices" style="width: 100%">
      <el-table-column prop="deviceId" label="设备 ID" />
      <el-table-column prop="deviceName" label="设备名称" />
      <el-table-column prop="model" label="设备型号" />
      <el-table-column prop="category" label="设备分类" />
      <el-table-column prop="brand" label="设备品牌" />
      <el-table-column prop="serialNumber" label="序列号" />
      <el-table-column prop="purchaseDate" label="购买日期" />
      <el-table-column prop="purchaseAmount" label="购买金额" />
      <el-table-column prop="supplier" label="供应商" />
      <el-table-column prop="warrantyPeriod" label="保修期（月）" />
      <el-table-column
          prop="status"
          label="设备状态"
          :formatter="formatStatus"
      />
      <el-table-column prop="departmentName" label="所属部门" />
      <el-table-column prop="location" label="设备存放位置" />
      <el-table-column prop="imageUrl" label="设备图片链接" />
      <el-table-column prop="remarks" label="备注信息" />
      <el-table-column label="分配类型" width="100">
        <template #default="scope">
          {{ scope.row.useType }}
        </template>
      </el-table-column>
      <el-table-column label="部门名称/使用人" width="180">
        <template #default="scope">
          <div v-if="scope.row.useType === '部门申请'">
            {{ scope.row.useDepartmentName }}
          </div>
          <div v-else>
            {{ scope.row.userName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button v-if="scope.row.status === 'in_use'" @click="returnDevice(scope.row)" type="warning">归还</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 设备归还抽屉 -->
    <el-drawer v-model="showReturnDrawer" title="归还设备" size="50%">
      <div v-if="returningDevice">
        <h2>确认归还设备</h2>
        <p>设备 ID: {{ returningDevice.deviceId }}</p>
        <p>设备名称: {{ returningDevice.deviceName }}</p>
        <el-form label-width="120px">
          <el-form-item label="归还日期:">
            <el-date-picker v-model="returningDevice.returnDate" type="date" placeholder="选择归还日期" />
          </el-form-item>
          <el-form-item label="归还备注:">
            <el-input v-model="returningDevice.returnRemarks" type="textarea" placeholder="输入归还备注" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="confirmReturn">确认归还</el-button>
            <el-button @click="showReturnDrawer = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import {queryDevices, queryDevicesInUse, returnDeviceApi} from '@/api/device.js';

// 查询设备信息
const queryDevice = ref({
  deviceId: '',
  status: '',
  deviceName: '',
  model: '',
  category: '',
  brand: '',
  serialNumber: ''
});

// 设备列表
const devices = ref([]);

// 正在归还的设备信息
const returningDevice = ref(null);

// 页面加载时默认查询一次数据
onMounted(() => {
  query();
});

// 设备查询
const query = async () => {
  try {
    const response = await queryDevicesInUse(queryDevice.value);
    devices.value = response.data || [];
  } catch (error) {
    console.error(error);
  }
};

// 归还设备
const returnDevice = (device) => {
  returningDevice.value = {...device, returnDate: null, returnRemarks: ''};
  showReturnDrawer.value = true;
};

// 确认归还
const confirmReturn = async () => {
  try {
    // 格式化归还日期为字符串
    const formattedReturnDate = formatDateTime(returningDevice.value.returnDate);

    // 构建后端需要的归还参数
    const returnParams = {
      deviceId: returningDevice.value.deviceId,
      returnDate: formattedReturnDate,
      returnRemarks: returningDevice.value.returnRemarks || ''
    };

    // 调用后端归还接口
    await returnDeviceApi(returnParams);

    // 更新本地设备列表状态
    const index = devices.value.findIndex(item => item.deviceId === returningDevice.value.deviceId);
    if (index !== -1) {
      devices.value[index].status = 'in_stock'; // 将设备状态改为库存中
      devices.value[index].useType = ''; // 清空分配类型
      devices.value[index].useDepartmentName = ''; // 清空使用部门
      devices.value[index].userName = ''; // 清空使用人
      devices.value[index].returnedDate = formattedReturnDate; // 设置归还时间
    }

    showReturnDrawer.value = false;
    uni.showToast({
      title: '设备归还成功',
      icon: 'success'
    });
  } catch (error) {
    console.error('设备归还失败:', error);
    uni.showToast({
      title: '设备归还失败',
      icon: 'error'
    });
  }
};

// 格式化设备状态
const formatStatus = (row, column, cellValue) => {
  const statusMap = {
    in_stock: '库存中',
    in_use: '使用中',
    under_maintenance: '维修中',
    disposed: '已报废'
  };
  return statusMap[cellValue] || '未知状态';
};

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return null;
  return date.toISOString().split('T')[0];
};

// 控制归还抽屉显示
const showReturnDrawer = ref(false);
</script>
